<!-- 学员收支 -->
<template>
  <el-card>
    <el-row>
      <el-col :span="8">
        <el-row class="m-b-8">
          <el-col :span="8" class="under">
            <el-text class="student">学员收支</el-text>
          </el-col>
        </el-row>
        <el-row>
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            label-width="80px"
            :size="formSize"
            status-icon
          >
            <el-form-item label="收支项目" prop="type" required>
              <el-select
                v-model="ruleForm.type"
                placeholder="请选择收支项目"
                @change="changeItemType"
                style="width: 220px"
              >
                <el-option label="请选择收支项目" value=""></el-option>
                <el-option
                  v-for="item in project"
                  :key="item.objectId"
                  :label="item.name"
                  :value="item.name"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="预收金额" prop="ReceivedMoney" required>
              <el-input
                v-model.number="ruleForm.ReceivedMoney"
                readonly
                placeholder="请输入收支金额"
              />
            </el-form-item>

            <el-form-item label="实际金额" prop="money" required>
              <el-input
                v-model.number="ruleForm.money"
                readonly
                placeholder="请输入实际金额"
              />
            </el-form-item>
            <el-row>
              <el-form-item prop="wechat" label="微信" required>
                <el-input
                  v-model.number="ruleForm.wechat"
                  @input="handleReceiveMoney"
                />
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item prop="alipay" label="支付宝" required>
                <el-input
                  v-model.number="ruleForm.alipay"
                  @input="handleReceiveMoney"
                />
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item prop="cash" label="现金" required>
                <el-input
                  v-model.number="ruleForm.cash"
                  @input="handleReceiveMoney"
                />
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item prop="rests" label="其它支付" required>
                <el-input
                  v-model.number="ruleForm.rests"
                  @input="handleReceiveMoney"
                />
              </el-form-item>
            </el-row>

            <el-form-item label="欠费金额" prop="Arrearage">
              <el-input v-model.number="ruleForm.Arrearage" readonly />
            </el-form-item>

            <el-form-item label="收费时间" prop="time" required>
              <el-date-picker
                v-model="ruleForm.time"
                type="date"
                placeholder="请选择收费时间"
              />
            </el-form-item>
            <el-form-item label="收费备注" prop="descr">
              <el-input
                v-model="ruleForm.descr"
                placeholder="请输入收费备注内容"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="success" @click="submitForm(ruleFormRef)">
                添加学员费用
              </el-button>
            </el-form-item>
          </el-form>
        </el-row>
      </el-col>
      <el-col :span="16">
        <el-row class="m-b-8 m-t-2">
          <el-button
            type="primary"
            size="large"
            :icon="RefreshRight"
            @click="handleRefresh"
          >
            刷新
          </el-button>
        </el-row>
        <!-- 表格 -->
        <el-row>
          <el-table
            ref="multipleTableRef"
            :data="tableData"
            style="width: 100%"
            show-overflow-tooltip
            fit
            table-layout="auto"
            border
            scrollbar-always-on
          >
            <el-table-column
              label="序号"
              type="index"
              width="60"
              header-align="center"
              align="center"
            />

            <el-table-column
              label="收支名称"
              width="120"
              header-align="center"
              align="center"
            >
              <template #default="scope">{{ scope.row.type }}</template>
            </el-table-column>

            <el-table-column
              label="类型"
              width="80"
              header-align="center"
              align="center"
            >
              <template #default="scope">
                <el-tag
                  effect="dark"
                  type="danger"
                  v-if="scope.row.isExpen == '支出'"
                  >{{ scope.row.isExpen }}
                </el-tag>
                <el-tag effect="dark" v-else>{{ scope.row.isExpen }} </el-tag>
              </template>
            </el-table-column>

            <el-table-column
              label="预收金额"
              width="120"
              header-align="center"
              align="center"
            >
              <template #default="scope">{{
                scope.row.ReceivedMoney
              }}</template>
            </el-table-column>

            <el-table-column
              label="实际金额"
              width="120"
              header-align="center"
              align="center"
              sortable
              prop="money"
            >
              <template #default="scope">
                <el-text v-if="scope.row.isExpen == '支出'" type="primary">
                  {{ -scope.row.money }}
                </el-text>
                <el-text v-else type="primary">
                  {{ scope.row.money }}
                </el-text>
              </template>
            </el-table-column>

            <el-table-column
              label="支付方式"
              header-align="center"
              align="center"
            >
              <el-table-column
                label="微信"
                width="100"
                header-align="center"
                align="center"
              >
                <template #default="scope">{{ scope.row.wechat }}</template>
              </el-table-column>
              <el-table-column
                label="支付宝"
                width="100"
                header-align="center"
                align="center"
              >
                <template #default="scope">{{ scope.row.alipay }}</template>
              </el-table-column>
              <el-table-column
                label="现金"
                width="100"
                header-align="center"
                align="center"
              >
                <template #default="scope">{{ scope.row.cash }}</template>
              </el-table-column>

              <el-table-column
                label="其它付款"
                width="100"
                header-align="center"
                align="center"
              >
                <template #default="scope">{{ scope.row.rests }}</template>
              </el-table-column>
            </el-table-column>

            <el-table-column
              label="欠费金额"
              width="100"
              header-align="center"
              align="center"
            >
              <template #default="scope">{{ scope.row.Arrearage }}</template>
            </el-table-column>

            <el-table-column
              label="生成时间"
              width="300"
              header-align="center"
              align="center"
            >
              <template #default="scope">{{
                scope.row.time.replace("T", " ").replace(".000Z", "")
              }}</template>
            </el-table-column>

            <el-table-column
              label="收支状态"
              width="100"
              header-align="center"
              align="center"
            >
              <template #default="scope">
                <el-text v-if="scope.row.state == '未审核'">
                  {{ scope.row.state }}</el-text
                >
                <el-text type="success" v-else> {{ scope.row.state }}</el-text>
              </template>
            </el-table-column>

            <el-table-column
              label="审核时间"
              width="300"
              header-align="center"
              align="center"
            >
              <template #default="scope">{{ scope.row.audit }}</template>
            </el-table-column>

            <el-table-column
              label="入账通道"
              width="100"
              header-align="center"
              align="center"
            >
              <template #default>
                <el-text>前台办理</el-text>
              </template>
            </el-table-column>

            <el-table-column
              label="备注"
              width="150"
              header-align="center"
              align="center"
            >
              <template #default="scope">{{ scope.row.descr }}</template>
            </el-table-column>

            <el-table-column
              label="操作"
              width="250"
              header-align="center"
              align="center"
            >
              <template #default="{ row }">
                <el-button
                  type="success"
                  round
                  size="small"
                  :icon="Money"
                  v-if="row.Arrearage"
                  @click="handlepay(row)"
                  >回款</el-button
                >

                <el-button
                  type="danger"
                  round
                  size="small"
                  :icon="Delete"
                  v-if="row.state === '未审核'"
                  @click="handleDel(row)"
                  >删除</el-button
                >
                <el-button
                  type="warning"
                  round
                  size="small"
                  :icon="Printer"
                  v-else
                  >打印</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-row>

        <el-dialog
          :title="title"
          v-model="dialogMoney"
          width="30%"
          destroy-on-close
        >
          <StuRefund
            v-model="dialogMoney"
            :Redata="RefundDate"
            @handleRefresh="handleRefresh"
          />
        </el-dialog>

        <el-config-provider :locale="locale" v-if="total">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 40]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-config-provider>
      </el-col>
    </el-row>
  </el-card>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { useRoute } from "vue-router";
import type { FormInstance } from "element-plus";
import { RefreshRight, Money, Delete, Printer } from "@element-plus/icons-vue";
import locale from "element-plus/es/locale/lang/zh-cn";
import StuRefund from "./Stu_refund.vue";
import {
  StuMoneyGet,
  StuMoney,
  StuMoneyDel,
  StuOutMoney,
  StuGet,
} from "../../../api/students";
import { StuExpendPost } from "../../../api/studentMoney";
import { ElMessage, ElMessageBox } from "element-plus";
import { ElTable } from "element-plus";
interface MoneyForm {
  studentId?: string;
  name: string;
  cardId: string;
  phone: string;
  carType: string;

  type: string;
  ReceivedMoney: number;
  money: number;
  wechat: number;
  alipay: number;
  cash: number;
  rests: number;
  Arrearage: number;
  time: string;
  descr: string;
  isExpen: string;
}
//学员Id
const route = useRoute();
let { objectId } = route.query as any;
StuGet(objectId).then((res) => {
  ruleForm.value.name = res.data.name;
  ruleForm.value.cardId = res.data.cardId;
  ruleForm.value.phone = res.data.tel;
  ruleForm.value.carType = res.data.carType;
});


const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = ref<MoneyForm>({
  studentId: objectId,
  name: "",
  cardId: "",
  phone: "",
  carType: "",

  type: "",
  ReceivedMoney: 0,
  money: 0,
  wechat: 0,
  alipay: 0,
  cash: 0,
  rests: 0,
  Arrearage: 0,
  time: "",
  descr: "",
  isExpen: "",
});

const handleReceiveMoney = () => {
  ruleForm.value.money =
    ruleForm.value.wechat +
    ruleForm.value.alipay +
    ruleForm.value.cash +
    ruleForm.value.rests;

  ruleForm.value.Arrearage =
    ruleForm.value.ReceivedMoney - ruleForm.value.money;

  if (ruleForm.value.Arrearage <= 0) {
    ruleForm.value.Arrearage = 0;
  }
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 缴费记录
      StuExpendPost(ruleForm.value).then(() => {
        formEl.resetFields();
        handleRefresh();
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

// const options = Array.from({ length: 10000 }).map((_, idx) => ({
//   value: `${idx + 1}`,
//   label: `${idx + 1}`,
// }));

// 分页条
const currentPage = ref(1);
// 每页显示条数
const pageSize = ref(10);
const total = ref(100);
const small = ref(false);
const background = ref(false);
const disabled = ref(false);
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  StuMoneyGet(currentPage.value, val, objectId).then((res) => {
    tableData.value = res.data.results;
    total.value = res.data.count;
  });
};
const handleCurrentChange = (val: number) => {
  // console.log(`当前页码: ${val}`)
  currentPage.value = val;
  StuMoneyGet(val, pageSize.value, objectId).then((res) => {
    tableData.value = res.data.results;
    total.value = res.data.count;
  });
};
const multipleTableRef = ref<InstanceType<typeof ElTable>>();

const tableData = ref<any>(null);
onMounted(() => {
  StuMoney(objectId).then((res) => {
    tableData.value = res.data.results;
    total.value = res.data.count;
  });
});

// 自定表尾计算方法
// 刷新数据
const handleRefresh = () => {
  StuMoney(objectId).then((res) => {
    tableData.value = res.data.results;
    total.value = res.data.results.length;
  });
};

// 删除数据
const handleDel = (row: any) => {
  ElMessageBox.confirm("确认删除此记录?", "温馨提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    center: true,
    type: "warning",
  })
    .then(() => {
      StuMoneyDel(row.objectId).then(() => {
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        for (let i in tableData.value) {
          if (tableData.value[i].objectId == row.objectId) {
            delete tableData.value[i];
          }
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
};
// 余额缴费
let title = "";
let RefundDate = ref("");
const dialogMoney = ref(false);
const handlepay = (row: any) => {

  dialogMoney.value = true;
  title = "回款" + ":" + row.type;
  RefundDate.value = JSON.stringify(row);
};
// 日期处理
// let time = new Date();
// console.log(time.toLocaleString().replace("/", "-").replace("/", "-"));

// 定义收支项目名
let project = ref<any>([]);
StuOutMoney().then((res) => {
  project.value = res.data.results;
});

const changeItemType = (val: string) => {
  project.value.forEach((item: any) => {
    if (item.name == val) {
      ruleForm.value.ReceivedMoney = Number(item.money);
      ruleForm.value.Arrearage = Number(item.money);
      ruleForm.value.isExpen = item.inOrexpen;
    }
  });
};
</script>

<style scoped>
.student {
  color: #666666;
  font-size: 20px;
  font-weight: lighter;
  margin-top: 20px;
  padding-bottom: 20px;
  padding-left: 20px;
}
</style>
